package jmind.core.support;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 简体、繁体 中文互转
 * @author xieweibo
 * @date 2015年7月27日
 */
public class ChineseConverter {
    public static enum Chinese {
        simplified, // 繁体---》简体
        traditional // 简体---》繁体
    }

    private final Properties charMap = new Properties();
    private final Set<String> conflictingSets = new HashSet<String>();
    private static final ChineseConverter[] converters = new ChineseConverter[2];

    /**
     *
     * @param converterType 0 for traditional and 1 for simplified
     * @return
     */
    private static ChineseConverter getInstance(Chinese chinese) {
        int converterType = chinese.ordinal();
        if (converters[converterType] == null) {
            synchronized (ChineseConverter.class) {
                if (converters[converterType] == null) {
                    converters[converterType] = new ChineseConverter(chinese.name() + "-chinese.properties");
                }
            }
        }
        return converters[converterType];

    }

    /**
     * 简体 ，繁体互转
     * @param text
     * @param converterType
     * @return
     */
    public static String convert(String text, Chinese converterType) {
        ChineseConverter instance = getInstance(converterType);
        return instance.convert(text);
    }

    private String convert(String in) {
        StringBuilder outString = new StringBuilder();
        StringBuilder stackString = new StringBuilder();

        for (int i = 0; i < in.length(); i++) {

            char c = in.charAt(i);
            String key = "" + c;
            stackString.append(key);

            if (conflictingSets.contains(stackString.toString())) {
            } else if (charMap.containsKey(stackString.toString())) {
                outString.append(charMap.get(stackString.toString()));
                stackString.setLength(0);
            } else {
                CharSequence sequence = stackString.subSequence(0, stackString.length() - 1);
                stackString.delete(0, stackString.length() - 1);
                flushStack(outString, new StringBuilder(sequence));
            }
        }

        flushStack(outString, stackString);
        return outString.toString();
    }

    private ChineseConverter(String propertyFile) {
        InputStream in = getClass().getClassLoader().getResourceAsStream(propertyFile);
        if (in != null) {
            try {
                charMap.load(in);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null)
                        in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            System.err.println("ZHConverter  in is null  " + propertyFile);
        }
        initializeHelper();
    }

    @SuppressWarnings("rawtypes")
    private void initializeHelper() {
        Map<String, Integer> stringPossibilities = new HashMap<String, Integer>();
        Iterator iter = charMap.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (key.length() >= 1) {
                for (int i = 0; i < (key.length()); i++) {
                    String keySubstring = key.substring(0, i + 1);
                    if (stringPossibilities.containsKey(keySubstring)) {
                        Integer integer = (Integer) (stringPossibilities.get(keySubstring));
                        stringPossibilities.put(keySubstring, new Integer(integer.intValue() + 1));

                    } else {
                        stringPossibilities.put(keySubstring, new Integer(1));
                    }

                }
            }
        }

        iter = stringPossibilities.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (((Integer) (stringPossibilities.get(key))).intValue() > 1) {
                conflictingSets.add(key);
            }
        }
    }

    private void flushStack(StringBuilder outString, StringBuilder stackString) {
        while (stackString.length() > 0) {
            if (charMap.containsKey(stackString.toString())) {
                outString.append(charMap.get(stackString.toString()));
                stackString.setLength(0);

            } else {
                outString.append("" + stackString.charAt(0));
                stackString.delete(0, 1);
            }

        }
    }

    //    public static void main(String[] args) {
    //
    //        String a = "谢伟波,此卡已无效,当前设备已超过服务兑换次数上限,请使用领取全屏影视会员的账号进行兑换,mac, key,uid 参数不能为空,抱歉,此卡已过期！";
    //        String b = ChineseConverter.convert(a, Chinese.traditional);
    //        System.out.println(b);
    //        System.out.println(ChineseConverter.convert(b, Chinese.simplified));
    //    }
}